#!/usr/bin/python
# -*- coding: utf-8 -*-
# encoding: utf-8
#客户端调用，用于查看API返回结果
#   https://github.com/okcoin-okex/open-api-v3-sdk          v3版接口
#   https://www.okb.com/docs/zh/#ett-README                 v3说明
import _thread
from datetime import datetime

from py_at.Bar import Bar
from py_at.at_struct import *
from excange.okiapi.OkcoinFutureAPI import OKCoinFuture
from excange.okiapi.OkcoinSpotAPI import OKCoinSpot
import numpy as np
#
# 初始化apikey，secretkey,url
#cheng
#apikey = '85c6e707-2081-48d4-972c-6817f4ad7fcd'
#secretkey = 'DDAE28A6A82AAF6B6A566DBFC0D57310'

# adong
# apikey= "79e0554b-4c36-4a76-a304-4f43aa40b418"
# secretkey= "F2549539841EE8AAA03C85EEBA7B944F"

#xiangke2
# apikey = "e5a48296-2877-4157-b270-c139d2716b94"
# secretkey= "545F6D49C762A0E738254E766A1DCA00"


#xiangke
# apikey = '15718ddb-7b21-407f-8bf1-4548b5691e43'
# secretkey = '16671948FA1EE957E8A67EF64459AF74'

#志涛哥
# apiKey: 6f930a48-7846-4d82-82e4-319e7980943c
# secretKey: 25E2FF1ADAA29C7959D3489427E2EF92
#okcoinRESTURL = 'www.okex.com'  # 请求注意：国内账号需要 修改为 www.okcoin.cn
#okcoinRESTURL = 'www.okcoin.com'   #请求注意：国内账号需要 修改为 www.okcoin.cn
#现货API
#okcoinSpot = OKCoinSpot(okcoinRESTURL,apikey,secretkey)

#期货API
#okcoinFuture = OKCoinFuture(okcoinRESTURL,apikey,secretkey)

# print (u' 现货行情 ')
# print (okcoinSpot.ticker('btc_usd'))
#
# print (u' 现货深度 ')
# print (okcoinSpot.depth('btc_usd'))

#print (u' 现货历史交易信息 ')
#print (okcoinSpot.trades())

#print (u' 用户现货账户信息 ')
#print (okcoinSpot.userinfo())

#print (u' 现货下单 ')
#print (okcoinSpot.trade('ltc_usd','buy','0.1','0.2'))

#print (u' 现货批量下单 ')
#print (okcoinSpot.batchTrade('ltc_usd','buy','[{price:0.1,amount:0.2},{price:0.1,amount:0.2}]'))

#print (u' 现货取消订单 ')
#print (okcoinSpot.cancelOrder('ltc_usd','18243073'))

#print (u' 现货订单信息查询 ')
#print (okcoinSpot.orderinfo('ltc_usd','18243644'))

#print (u' 现货批量订单信息查询 ')
#print (okcoinSpot.ordersinfo('ltc_usd','18243800,18243801,18243644','0'))

#print (u' 现货历史订单信息查询 ')
#print (okcoinSpot.orderHistory('ltc_usd','0','1','2'))
#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

# print (u' 期货行情信息')
#print(okcoinFuture.future_ticker('btc_usd', 'this_week'))

#
# print (u' 期货市场深度信息')
# print (okcoinFuture.future_depth('btc_usd','this_week','6'))

#print (u'期货虚拟合约的k线数据')
#print(okcoinFuture.future_kline('btc_usd','1hour','this_week','10','0'))

#print (u'期货交易记录信息') 
#print (okcoinFuture.future_trades('ltc_usd','this_week'))

#print (u'期货指数信息')
#print (okcoinFuture.future_index('ltc_usd'))

#print (u'美元人民币汇率')
#print (okcoinFuture.exchange_rate())

#print (u'获取预估交割价') 
#print (okcoinFuture.future_estimated_price('ltc_usd'))

#print (u'获取全仓账户信息')
#print (okcoinFuture.future_userinfo())

#print (u'获取全仓持仓信息')
#print (okcoinFuture.future_position('ltc_usd','this_week'))

# print (u'期货下单')
# # （1:开多   2:开空   3:平多   4:平空) ,( 对手价格(0 不是,1是) (杠杆倍数)
# print (okcoinFuture.future_trade('ltc_usd',
#                                  'this_week',
#                                  '0.1',     #价格
#                                  '1',         #数量
#                                  '1',        #1:开多   2:开空   3:平多   4:平空)
#                                  '0',       #( 对手价格(0 不是,1是)
#                                  '20'))  #(杠杆倍数)

#print (u'期货批量下单')
#print (okcoinFuture.future_batchTrade('ltc_usd','this_week','[{price:0.1,amount:1,type:1,match_price:0},{price:0.1,amount:3,type:1,match_price:0}]','20'))

#print (u'期货取消订单')
#print (okcoinFuture.future_cancel('ltc_usd','this_week','47231499'))

#print (u'期货获取订单信息')
#print (okcoinFuture.future_orderinfo('ltc_usd','this_week','47231812','0','1','2'))

#print (u'期货逐仓账户信息')
#print (okcoinFuture.future_userinfo_4fix())

#print (u'期货逐仓持仓信息')
#print (okcoinFuture.future_position_4fix('ltc_usd','this_week',1))


import threading
import copy

TRADETYPE = {1:"开多",2:"开空",3:"平多",4:"平空" }  #交易类型
TRADETSTATUS = {0:"等待成交", 1:"部分成交",2:"全部成交",-1:"撤单",4:"撤单处理中",5:"撤单中"}  #订单状态

class Account():
    def __init__(self,apikey,secretkey,url,positiontype,userinfoname):
        self.apikey = apikey #
        self.secretkey =secretkey#
        self.okcoinRESTURL = url  # 'www.okex.com'  # 请求注意：国内账号需要 修改为 www.okcoin.cn
        self.positiontype = positiontype   #仓位是逐仓还是全仓
        self.userinfoName = userinfoname
        # 现货API 未启用
        #self.okcoinSpot = OKCoinSpot(okcoinRESTURL, self.apikey, self.secretkey)
        # 期货API
        self.okcoinFuture = OKCoinFuture(self.okcoinRESTURL, self.apikey, self.secretkey)
        self.linkeThead={}  #k线线程
        self.tickerThead={}  #行情线程
        #self.future_userinfo_4fix()  #启用逐仓查询
        #self.future_position_4fix()   #这个启动之后自动查询所有持仓 暂时不启动
        self.Positions={}    #定义账户持仓信息


    def Register(self):
        '''订阅各k线数据'''
        self.requestLinke('btc_usd', '5min', 'this_week', '1', '0')
        #self.requestTicker()

    #订阅k线-----------------------------------------
    def requestLinke(self,symbol,type='1min',contract_type='this_week',size='1',since='0'):
        """订阅k线"""
        #_thread.start_new_thread(self._On_Linke, ())  # 开始进行返回on函数注册
        if not self.linkeThead.get(symbol):
            self.linkeThead[symbol] = threading.Thread(target=self._On_Linke,args=(symbol,type,contract_type,size,since,))
            self.linkeThead[symbol].start()

    def _On_Linke(self,symbol,type,contract_type,size,since):
        """返回on_link"""
        while True:
            time.sleep(1)
            doc=self.okcoinFuture.future_kline(symbol, type, contract_type, size, since)

            if(doc==None):
                print('本次出问题了  空')
                continue
            doc=doc[0]
            bar=Bar(doc[0], doc[2], doc[3], doc[1], doc[4], doc[6],doc[5], doc[0][0:10])
            bar._sybom=symbol
            self.On_Linke(bar)
            #self.On_Linke(self.okcoinFuture.future_kline('btc_usd', '1min', 'this_week', '5', '0'))
    def On_Linke(self,linkedate):
        '''需要在前台实现'''
        print(linkedate)


    #订阅实时行情------------------------------------------------------

    def ReqSubscribeMarketData(self, symbol, contract_type="quarter"):
        """订阅实时行情
        合约类型: this_week:当周 next_week:下周 quarter:季度
        """

        #_thread.start_new_thread(self._On_Ticker, ())  # 开始进行返回on函数注册
        #一个合约一个线程 self.tickerThead为线程dict
        if not self.tickerThead.get(symbol):
            self.tickerThead[symbol]=threading.Thread(target=self._On_Ticker,args=(symbol,contract_type))
            self.tickerThead[symbol].start()

    def _On_Ticker(self,symbol='btc_usd',contract_type='this_week'):
        """返回On_Ticker"""
        while True:
            time.sleep(1)
            ticktemp=self.okcoinFuture.future_ticker(symbol, contract_type)
            if ticktemp==None:
                print('本次出问题了  空')
                continue
            if not ticktemp.get('ticker'):
                print("本次出问题了 不是空 但是这个里面没有key")
                continue
            tick=Tick()
            tick.Instrument = symbol
            tick.LastPrice = ticktemp['ticker']['last']
            tick.AskPrice = ticktemp['ticker']['buy']
            tick.BidPrice = ticktemp['ticker']['sell']
            tick.Strtime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(int(ticktemp['date'])))  # 字符串格式
            tick.UpdateTime = datetime.strptime(tick.Strtime,"%Y-%m-%d %H:%M:%S")
            tick.TradingDay = tick.Strtime[0:10]  # 字符串格式
            self.On_Ticker(tick)
    def On_Ticker(self,ticker):
        print(ticker)

    #发送订单---------------------------------------------------------------
    def future_trade(self,symbol,contract_type,price,amount,type,match_price,lever_rate):
        _thread.start_new_thread(self._On_future_trade, (symbol,contract_type,price,amount,type,match_price,lever_rate,))

    def _On_future_trade(self,symbol,contract_type,price,amount,type,match_price,lever_rate):
        print('商品 {0} 合约{1} 价格{2} 数量{3} 方向{4} 对手价{5} 杠杆倍数{6}'.format(symbol,contract_type,price,amount,type,match_price,lever_rate))
        temp=self.okcoinFuture.future_trade(symbol,
                                  contract_type,
                                  price,  # 价格
                                  amount,  # 数量
                                  type,  # 1:开多   2:开空   3:平多   4:平空)
                                  match_price,  # ( 对手价格(0 不是,1是)
                                  lever_rate)  #杠杆倍数
        self.On_future_trade(temp)
    def On_future_trade(self,futrue_trade):
        """需要前台实现  默认返回结果"""
        print(futrue_trade)




    """查询用户信息 -----------------------------------------------"""
    def future_userinfo(self,xunhuan=False):  #可同时兼容全仓以及持仓方案的查询
        """查询账户信息"""
        _thread.start_new_thread(self._On_futur_userinof, (xunhuan,))
    def _On_futur_userinof(self,xunhuan):
        """查询账户返回信息"""
        while True:
            #print("{0}开始去爬了".format(self.userinfoName))
            if self.positiontype == "zhu":  # 初始化的时候已经确定是全仓还是逐仓
                returnposition = self.okcoinFuture.future_userinfo_4fix()
            else:
                returnposition = self.okcoinFuture.future_userinfo()
            #print(temp)   #后台返回基础数据
            if returnposition ==None:
                print("本次查询账户信息处错误了")
                continue
            tempdict = []
            returnposition =json.loads(returnposition)  #格式化为json
            returnposition = returnposition['info']        #取出实际使用的数据
            for k,v in returnposition.items():          # 遍历数据
                if self.positiontype =="zhu":
                    if len(v['contracts'])==0:     #如果没有详细list
                        continue     #退出本次循环
                    contracts = v['contracts'][0]  #如果存在那么
                #     if v['rights']==0:    #如果额为0 退出循环
                #         continue
                # else:
                #     if v['account_rights'] == 0:  #如果额为0 退出循环
                #         continue

                tradingAccount = TradingAccount()
                tradingAccount.AccountId =self.userinfoName
                tradingAccount.symbo = k
                tradingAccount.contract_type = contracts['contract_type'] if self.positiontype=="zhu" else ""
                tradingAccount.contract_id = contracts['contract_id'] if self.positiontype=="zhu" else ''
                tradingAccount.PreBalance  =0.0
                tradingAccount.PositionProfit = contracts['unprofit']if self.positiontype=="zhu" else  v['profit_unreal']   #未实现盈亏  持仓利率
                tradingAccount.CloseProfit = contracts['unprofit'] if self.positiontype=="zhu" else v['profit_real']       #已实现盈亏   平仓利润
                tradingAccount.Commission = 0.0
                tradingAccount.CurrMargin = contracts['bond'] if self.positiontype=="zhu" else v['keep_deposit']         #当前保证金
                tradingAccount.FrozenCash =contracts['freeze'] if self.positiontype=="zhu" else 0  # 冻结 contracts['freeze']
                tradingAccount.Available = contracts['available'] if self.positiontype=="zhu" else  v['account_rights']-v['keep_deposit']  # 可用     contracts['available'],
                tradingAccount.Fund = v['rights'] if self.positiontype=="zhu" else v['account_rights']  # 账户总额    v['rights']
                if tradingAccount.Fund>0:
                    tradingAccount.Risk = tradingAccount.CurrMargin /tradingAccount.Fund    #持仓保证金/客户权益   计算的风险度
                else:
                    tradingAccount.Risk = 0

                self.On_futur_userinof(tradingAccount)       #推送信息到前台
                #tempdict.append(tradingAccount.__dict__)

            #print(tempdict)
            if xunhuan==False:  #如果循环条件为False  那么直接跳出当前循环

                break
            else:
                # self.On_futur_userinof(tempdict)
                time.sleep(3)      #否则进入无限循环状态


    def On_futur_userinof(self,future_userinfo):
        """需要前台实现"""
        print(future_userinfo)


    """查询账户持仓信息----------------------------------------"""
    def future_position(self, sybom=[], contract_type="quarter", type=1):
        """
        目前固定模式  this_week以后可以分开
        :param sybom: 'btc_usd'
        :param contract_type: 'this_week'
        :param type: 1
        :return:
        """
        _thread.start_new_thread(self._On_future_position, (sybom, contract_type, type,))

    def _On_future_position(self, sybom, contract_type, type=1):
        while True:

            #_thread.start_new_thread(self.SelectPosition,(i,contract_type,type,))  暂时不能用线程因为这个地方如果用线程了  那么线程启动的一瞬间下面直接就开始了  开始以后还有些并没有返回  那就造成有些查询不准确了
            position=self.SelectPosition(sybom, contract_type,type,False)        #这里面包装了全仓和逐仓以及所有品种的查询
            self.On_future_position(position)   #查询完毕以后直接返回这个相应函数
            time.sleep(3)  # 每3秒进行查询

    #-----------------------------这个方法单独的函数  用于遍历请求查询仓位信息
    def SelectPosition(self,sybom,contract_type,type,tongji=True):
        """
        查询用户持仓
        :param sybom:
        :param contract_type:
        :param type:
        :params tongji=False   是否是统计发出的请求  如果是统计的请求 那么只需要返回持仓数量即可  否则返回对象list
        :return:
        """
        if len(sybom) == 0:
            sybom = ['btc_usd','eos_usd', 'ltc_usd', 'eth_usd', 'etc_usd', 'bch_usd']
        positions={}
        positionsdict={}
        for i in sybom:
            positions[i]={}

            if self.positiontype=="zhu":                     #初始化的时候已经确定是全仓还是逐仓
                temp = self.okcoinFuture.future_position_4fix(i, contract_type, type)  #逐仓
            else:
                temp =self.okcoinFuture.future_position(i, contract_type)   #全仓

            # 如果没有错误  那么拼接并且返回
            temp = json.loads(temp)
            #测试用  上面是实盘用
            # temp ={'result': True,
            #              'holding': [{'contract_id': 201812280000013,
            #              'sell_price_avg': 6344.8399369,
            #               'sell_bond': 0.04566391,
            #               'sell_profit_lossratio': '-2.92',
            #                'buy_bond': 0,
            #                'buy_available': 0,
            #                 'buy_flatprice': '0.00',
            #                 'buy_price_cost': 6376.66,
            #                  'buy_risk_rate': '1,000,000.00',
            #                   'sell_price_cost': 5333.01,
            #                    'buy_profit_lossratio': '0.00',
            #                     'sell_available': 10,
            #                      'buy_price_avg': 6376.66,
            #                       'contract_type': 'quarter',
            #                        'sell_flatprice': '6,972.04',
            #                        'symbol': 'btc_usd',
            #                         'create_date': 1536915109000,
            #                         'lever_rate': 10,
            #                         'sell_risk_rate': '281.27',
            #                          'profit_real': 0,
            #                          'sell_amount': 10,
            #                          'buy_amount': 0}]}
            if (temp.get('holding') and len(temp.get('holding')) > 0):
                positions[i]['Long'] = temp['holding'][0]['buy_amount']   #用于仓位统计
                positions[i]['Short'] = temp['holding'][0]['sell_amount'] #用于仓位统计
                if tongji==False:                 #如果不是统计了 往下操作
                    temp = temp['holding'][0]

                    if temp['buy_amount']>0:   #这个是用于前台显示的的
                        positionField = PositionField()
                        positionField.AccountId = self.userinfoName

                        positionField.InstrumentID=temp['symbol']
                        positionField.Direction=DirectType.Buy
                        positionField.Price=temp['buy_price_avg']
                        positionField.Position = temp['buy_amount']
                        positionField.available = temp['buy_available']
                        positionField.bond = temp['buy_bond'] if temp.get('buy_bond') else 0
                        #positionField.PositionProfit=temp['buy_profit_real']
                        positionField.profit_lossratio = temp['buy_profit_lossratio'] if temp.get('buy_profit_lossratio') else 0
                        positionField.flatprice = temp['buy_flatprice'] if temp.get('buy_flatprice') else 0
                        positionsdict['{0}_{1}'.format(temp['symbol'],0)]=positionField
                    if temp['sell_amount']>0:   #这个是用于前台显示的的
                        positionField = PositionField()
                        positionField.AccountId =self.userinfoName
                        positionField.InstrumentID = temp['symbol']
                        positionField.Direction = DirectType.Sell
                        positionField.Price = temp['sell_price_avg']
                        positionField.Position = temp['sell_amount']
                        positionField.available = temp['sell_available']
                        positionField.bond = temp['sell_bond'] if temp.get('sell_bond') else 0
                        #positionField.PositionProfit = temp['sell_profit_real']
                        #positionField.CloseProfit = temp['sell_profit_real']
                        positionField.profit_lossratio = temp['sell_profit_lossratio'] if temp.get('sell_profit_lossratio') else 0
                        positionField.flatprice = temp['sell_flatprice'] if temp.get('sell_flatprice') else 0
                        positionsdict['{0}_{1}'.format(temp['symbol'], 1)] = positionField


            # else:                                     #空持仓
            #     positionField = PositionField()
            #     positionField.AccountId = self.userinfoName
            #     positionField.InstrumentID = i
            #     positionField.Direction = DirectType.Buy
            #     positionField.Price = 0
            #     positionField.Position = 0
            #     positionField.available =0
            #     positionField.bond = 0
            #     # positionField.PositionProfit=temp['buy_profit_real']
            #     positionField.CloseProfit = 0
            #     positionField.profit_lossratio = 0
            #     positionField.flatprice = 0
            #     # positionField = positionField.__dict__
            #
            #     sellposition = copy.deepcopy(positionField)  #拷贝一份Short仓位的
            #     sellposition["Direction"] =DirectType.Sell
            #     # positionsdict['{0}_{1}'.format(i, 0)] = positionField
            #     # positionsdict['{0}_{1}'.format(i, 1)] = sellposition
            #     positions[i]['Long'] = 0
            #     positions[i]['Short'] = 0

        if tongji==True:  #如果是统计 那么只用返回统计的持仓数量
            return positions
        else:
            return positionsdict   #如果不是统计 那么需要返回所有的持仓对象list


    def On_future_position(self, position):
        print(position)

    """查询账户交易记录"""
    #---------------------------------------------------------------------------—————————————查询账户交易记录
    #def future_orderinfo(self, symbol, contractType, orderId, status, currentPage, pageLength):
    def future_order_info(self,sybom=[],contractType='quarter',orderId=-1, status=2,currentPage=0, pageLength=5):
        """
        :param sybom: 合约名btc_usd ltc_usd eth_usd etc_usd bch_usd
        :param contractType:合约类型合约类型: this_week:当周 next_week:下周 quarter:季度
        :param orderId: 交易id订单ID -1:查询指定状态的订单，否则查询相应订单号的订单
        :param status:非必填项    查询状态 1:未完成的订单 2:已经完成的订单
        :param currentPage:当前页数
        :param pageLength:每页获取条数，最多不超过50
        :return:
        """
        _thread.start_new_thread(self._On_future_order_info,(sybom,contractType,orderId,status,currentPage,pageLength))
    def _On_future_order_info(self,sybom,contractType,orderId,status,currentPage,pageLength):
        while True:                 #循环查询代码  暂时屏蔽
            order_infos = self.select_order_infos(sybom,contractType,orderId,status,currentPage,pageLength)
            time.sleep(5)
            self.On_future_order_info(order_infos)

    def select_order_infos(self,sybom,contractType,orderId,status,currentPage,pageLength):
        """遍历查询所有合约所有类型的交易记录，然后按照时间排序，然后返回（或者这里不排序 到前台排序也可以）"""
        if len(sybom)==0:
            sybom = ['btc_usd', 'eos_usd', 'ltc_usd', 'eth_usd', 'etc_usd', 'bch_usd']   #所有合约 遍历查询
        orderFieldlist = []
        tempzhuanhuan = {'多':DirectType.Buy,'空':DirectType.Sell,'开':OffsetType.Open,'平':OffsetType.Close}
        for i in sybom:
            print('{0} {1} {2} {3} {4} {5}'.format(i,contractType,orderId,status,currentPage,pageLength))
            temp =self.okcoinFuture.future_orderinfo(i,contractType,orderId,status,currentPage,pageLength)  #查询所有订单信息
            temp = json.loads(temp)
            """增加了一个注释"""
            if temp.get("orders") and len(temp.get('orders'))>0:
                for i in temp['orders']:
                    orderField = OrderField()
                    orderField.AccountId =self.userinfoName

                    orderField.Volume = i['amount']
                    orderField.Countract_name = i['contract_name']
                    orderField.InsertTime = timeStamp(i['create_date'])
                    orderField.TradeVolume = i['deal_amount']
                    orderField.Fee = i['fee']
                    orderField.OrderID = i['order_id']
                    orderField.LimitPrice = i['price']
                    orderField.AvgPrice = i['price_avg']
                    #orderField.Status =TRADETSTATUS[i['status']]
                    orderField.Status= OrderStatus.Filled   #status: 订单状态(0等待成交 1部分成交 2全部成交 -1撤单 4撤单处理中 5撤单中)
                    orderField.StatusMsg = TRADETSTATUS[i['status']]
                    orderField.InstrumentID = i['symbol']        #这个是否能和上面的Countract_name 结合下
                    # type: 订单类型 1：开多 2：开空 3：平多 4： 平空
                    orderField.Direction= tempzhuanhuan[TRADETYPE[i['type']][0]]
                    orderField.Offset = tempzhuanhuan[TRADETYPE[i['type']][1]]


                    orderField.Unit_amount =i['unit_amount']
                    orderField.Lever_rate =i['lever_rate']
                    orderFieldlist.append(orderField.__dict__)
        return orderFieldlist


    #订单查询回调函数
    def On_future_order_info(self,order_infos):
        print(order_infos)
    #---------------------------------------------------------------------------------------------------查询账户交易记录


    #---------------------------------------------------------------------------------------------------取消订单
    #取消订单
    def future_cancel(self,sybom,orderid,quarter=None):
        _thread.start_new_thread(self.okcoinFuture.future_cancel,(sybom,quarter,orderid))



















    @staticmethod
    def read_data_test(stra):
        """取历史K线数据,并执行策略回测"""
        # 取数据
        ddoc = read_from_mq(stra)  # 取历史库
        if (ddoc == None):
            print('初始化失败  ok又他妈挂了')
            return
        # print params os strategy
        # stra.OnOrder = self.on_order    # 这个地方 用于订单回调data 没有实现  ma也没有实现 但是这里上面赋值了 所以这个地方会回调 移动到下面了
        print('开始加载策略%s' % stra.ID)
        for p in stra.Params:
            print("参数为{0}:{1}".format(p, stra.Params[p]))

        lasttime = ddoc[-1][0]
        #ddoc=np.array(ddoc)

        for doc in ddoc:
            bar = Bar(doc[0], doc[2], doc[3], doc[1], doc[4], doc[6],
                      doc[5],doc[0][0:10],stra.Instrument)
            #stra.__new_min_bar__(bar)  # 调Data的onbar
        # stra.CurrMin = ddoc[-1][0]  #不使用tick不用这个 设置最后1分钟数据为加载数据库最后的数据

            #上面的1分钟调用方法  下面是任意分钟任意时间调用

            for data in stra.Datas:
                data.Bars = np.append(data.Bars, bar)
                data.D = np.append(data.D, bar.D)
                data.H = np.append(data.H, bar.H)
                data.L = np.append(data.L, bar.L)
                data.O = np.append(data.O, bar.O)
                data.C = np.append(data.C, bar.C)
                data.V = np.append(data.V, bar.V)
                data.I = np.append(data.I, bar.I)
                date = bar.TD #原来使用真实日期做的HighD,现在更改为交易日期
                if len(data.DateD) == 0 or data.DateD[0] != date:
                    data.DateD.insert(0, date)
                    data.OpenD.insert(0, bar.O)
                    data.HighD.insert(0, bar.H)
                    data.LowD.insert(0, bar.L)
                    data.CloseD.insert(0, bar.C)
                else:  # 如果还是当前天 那么就更新最高最低和收盘
                    data.HighD[0] = max(data.HighD[0], bar.H)
                    data.LowD[0] = min(data.LowD[0], bar.L)
                    data.CloseD[0] = bar.C
                #stra.__update_Day_bar__(bar)     #这个函数最后调用了策略的_BarUpdate
                data.BarUpdate(data, bar=bar)
            stra.Datas[0].CurrMin = lasttime
        print("orders:{0}, bars:{1}".format(len(stra.Orders), len(stra.Bars)))


        print("历史数据读取并且加载完毕了.")




# ----------------------------------------------------------------------下面是公共函数   私有的公共函数
def read_from_mq(stra, Type=0):
    """netMQ"""
    # https://www.okex.com/api/v1/future_kline.do?symbol=btc_usd&type=1min&contract_type=quarter
    # www.okb.com  有时候访问不了
    okcoinFuture = OKCoinFuture("www.okex.com", "15718ddb-7b21-407f-8bf1-4548b5691e43",
                                "16671948FA1EE957E8A67EF64459AF74")
    # okcoinFuture.future_kline('btc_usd', '1hour', 'this_week', '10', '0')1min : 1分钟
    # 3min : 3分钟          5min : 5分钟         15min : 15分钟      30min : 30分钟       1day : 1日      3day : 3日     1week : 1周      1hour : 1小时     2hour : 2小时    4hour : 4小时  6hour : 6小时     12hour : 12小时
    # TODO 这个地方需要修改
    zhuanhuan = {'IntervalType.Minute': 'min', 'IntervalType.Hour': 'hour', 'IntervalType.Day': 'day',
                 'IntervalType.Week': 'week'}
    zhuanhuan = {'Minute': 'min', 'Hour': 'hour', 'Day': 'day',
                 'Week': 'week'}
    stra.loadZhouqi = '{0}{1}'.format(stra.Interval, zhuanhuan[stra.IntervalType.name])
    gzipper = okcoinFuture.future_kline(stra.Instrument, stra.loadZhouqi, 'quarter', '3600', '0')
    return gzipper


#毫秒时间戳转换为普通时间
def timeStamp(timeNum):
    timeStamp = float(timeNum/1000)
    timeArray = time.localtime(timeStamp)
    otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
    return otherStyleTime
def xiangying(linkedate):
    if(linkedate._sybom=='btc_usd'):
        print('比特币行情来了{0}'.format(linkedate._sybom))
        print(linkedate)
    if (linkedate._sybom == 'ltc_usd'):
        print('莱特币行情来了{0}'.format(linkedate._sybom))
        print(linkedate)
def jiaoyixiangying(result):
    print(result)

if __name__ == '__main__':
    pass



#----------------------------------------------------------------------账户当前权益情况
    apikey = "79e0554b-4c36-4a76-a304-4f43aa40b418"
    secretkey= "F2549539841EE8AAA03C85EEBA7B944F",
    url = "www.okex.com",
    positiontype= "quan"
    a = Account(apikey, secretkey, url,'quan')
    # balance: 账户余额
    # available: 合约可用
    # balance: 账户(合约)余额
    # bond: 固定保证金
    # contract_id: 合约ID
    # contract_type: 合约类别
    # freeze: 冻结
    # profit: 已实现盈亏
    # unprofit: 未实现盈亏
    # rights: 账户权益
    temp = a.okcoinFuture.future_position('bch_usd','quarter')  #获取用户持仓获取OKEX合约账户信息 （全仓）
    #temp =a.okcoinFuture.future_position_4fix('bch_usd','quarter',1)
    #temp =a.okcoinFuture.future_userinfo()          #全仓账户信息
    #temp = a.okcoinFuture.future_userinfo_4fix()     #逐仓账户信息
    print(temp)
    temp = json.loads(temp)
    temp = temp["info"]
    for k, v in temp.items():
        contracts = v['contracts'][0]
        print('合约{0}，账户余额{1}，合约可用{2}，账户余额{3}，固定保证金{4}，合约id{5}，合约类别{6}，冻结{7}，实现盈亏{8}，未实现盈亏{9},账户权益{10}'.format(
            k,
            v['balance'],
            contracts['available'],
            contracts['balance'],
            contracts['bond'],
            contracts['contract_id'],
            contracts['contract_type'],
            contracts['freeze'],
            contracts['profit'],
            contracts['unprofit'],
            v['rights']))
#------------------------------------------------------------------------------------------------------------------

#---------------------------------------获取逐仓持仓信息-----------------------------------------------------------
    # #初始化apikey，secretkey, url
    # apikey = 'ca52c5f3-eed9-41f6-92bb-7b2e11755ecd'
    # secretkey = '37832CB5AA308CBF378B8467580EB7EB'
    #
    # # apikey = '11f24269-d024-4299-854e-f7369eabf638'
    # # secretkey = 'E339CDA4A5173C6797C57DCF5D862899'
    #
    # # 志涛哥
    # # apiKey: 6f930a48-7846-4d82-82e4-319e7980943c
    # # secretKey: 25E2FF1ADAA29C7959D3489427E2EF92
    # okcoinRESTURL = 'www.okb.com'  # 请求注意：国内账号需要 修改为 www.okcoin.cn
    # # okcoinRESTURL = 'www.okcoin.com'   #请求注意：国内账号需要 修改为 www.okcoin.cn
    # # 现货API
    # okcoinSpot = OKCoinSpot(okcoinRESTURL, apikey, secretkey)
    #
    # # 期货API
    # okcoinFuture = OKCoinFuture(okcoinRESTURL, apikey, secretkey)
    #
    # okcoinRESTURL = 'www.okb.com'  # 请求注意：国内账号需要 修改为 www.okcoin.cn
    #
    # a=Account(apikey,secretkey,okcoinRESTURL)
    # temp = okcoinFuture.future_position_4fix('btc_usd','this_week',1)
    # temp = json.loads(temp)
    # print(temp)
#-----------------------------------------------------------------------------------------------------------------


